var callBackDayFee = function dayFeeClick(param) {
	if ( param.data.code != "") {
		var pageData = jQuery.extend(true, {}, paramTabPage[tabId]);
		//param.data.value取散点图的数据，param.data.coords取线图数据
		if((param.data.value[0]*param.data.value[1]>=0)||(param.data.coords&&param.data.coords[1][0]*param.data.coords[1][1]>=0)){	
			if(param.data.drgDesc==undefined){
				pageData.name = param.data.name;
			}else{
				
				pageData.name = "("+param.data.code+")"+param.data.drgDesc;
			}
			//alert(param.data.drgDesc);
			pageData.drgCode = param.data.code;
			openTab('/pages/keyDiseaseGroup/keyDisGroAnal13Quad.jsp', '重点病组分析病组详情','keyDisGroupAnalysisDetailDayFee13', 'keyDisGroupAnalysisDetailDayFee13',pageData);
		}
		//param.data.value取散点图的数据，param.data.coords取线图数据
		else if((param.data.value[0]>0&&param.data.value[1]<0)||(param.data.coords&&param.data.coords[1][0]>0&&param.data.coords[1][1]<0)){
			if(param.data.desc==undefined){
				pageData.name = param.data.name;
			}else{
				pageData.name = "("+param.data.code+")"+param.data.desc;
			}
			pageData.drgCode = param.data.code;
			openTab('/pages/keyDiseaseGroup/keyDisGroAnal4Quad.jsp', '重点病组分析病组详情','keyDisGroupAnalysisDetailDayFee4', 'keyDisGroupAnalysisDetailDayFee4',pageData);
		}
		//param.data.value取散点图的数据，param.data.coords取线图数据
		else if((param.data.value[0]<0&&param.data.value[1]>0)||(param.data.coords&&param.data.coords[1][0]<0&&param.data.coords[1][1]>0)){
			if(param.data.desc==undefined){
				pageData.name = param.data.name;
			}else{
				pageData.name = "("+param.data.code+")"+param.data.desc;
			}
			pageData.drgCode = param.data.code;
			openTab('/pages/keyDiseaseGroup/keyDisGroAnal2Quad.jsp', '重点病组分析病组详情','keyDisGroupAnalysisDetailDayFee2', 'keyDisGroupAnalysisDetailDayFee2',pageData);
		}
	}
}
	
var callBackFeeDrug = function feeDrugClick(param) {
	var pageData = jQuery.extend(true, {}, paramTabPage[tabId]);
	if ( param.data.code ) {
		if(param.data.desc==undefined){
			pageData.name = param.data.name;
		}else{
			pageData.name = "("+param.data.code+")"+param.data.desc;
		}
		pageData.drgCode = param.data.code;
		openTab('/pages/keyDiseaseGroup/keyDisGroAnalFeeDrug.jsp', '重点病组分析病组详情','keyDisGroupAnalysisDetailFeeDrug', 'keyDisGroupAnalysisDetailFeeDrug',pageData);
	}
}
$(function(){
	
	showCondition(true, 1, 1, 1, [0, 0, 1,1,1]);//加载查询条件
	// 重点病组展示的指标
//	$("#searchcq").children().eq(2).find("a").eq(2).remove();//移除 检测时间 自定义 选项
	// 重新给比较类型赋值
	paramTabPage[tabId].compareType = $("#searchcq").children().eq(3).find("a.active").attr("data-value");
	paramTabPage[tabId].quadData = {};//用于存储绘制象限图的数据
	// 如果已经选择了科室，隐藏上面的tab 页签
	if(paramTabPage[tabId].oldDepCode != null && paramTabPage[tabId].oldDepCode != "") {
		paramTabPage[tabId].depCode = paramTabPage[tabId].oldDepCode ;
		$('#'+tabId+' #keyDisGroupTab li').css("display","none") ;
		// 科室下的重点病组隐藏右侧饼图
		$('#'+tabId+' #keyGroupChart').parent().attr("class","col-xs-12") ;
		$('#'+tabId+' #disGroupPropChart').parent().parent().css("display","none") ;
	}  
	
	//加载科室信息
	loadAllDepKeyDisGroup() ;
	// 重点病组表格展示的列
	var groupTableColumns = [
				                {
				                	 "data":"ccode",
				                	 "render":function(obj, type, full){
				                		 return  full.ccode+"-"+full.ddesc ;
				                	 }
			                	},
			                  	{"data": "InCaseCnt",
			                		"render":function(obj, type, full) {
			                			if(full.InCaseCnt == 0){
	        		                    	return full.InCaseCnt ;
			                			} else {
	        		                    	return "<a href=\"javascript:void(0);\" onclick= \"loadCaseDtl('入组病例数','"+full.ccode+"','drgs', 'InCaseCnt')\">"+full.InCaseCnt+"</a>";
			                			}
        		                    }
		                  		},
			                  	{"data": "CMI"},
			                  	{"data": "TotalWeight", "render": function(obj, type, full){
			                  		return formatNumber(full.TotalWeight);
			                  	}},
			                  	{"data": "AvgDays"},
			                  	{"data": "AvgFee", "render": function(obj, type, full){
			                  		return formatNumber(full.AvgFee)
			                  	}},
			                  	{"data": "RiskLevel","render":function(obj, type, full){
			                  		var str = "" ;
				                  		switch(Number(full.RiskLevel)) {
				                  	        case 0: {
				                  	            str = "无风险" ;break ;
				                  	        }
				                  	        case 1: {
				                  	        	str = "低风险" ;break ;
				                  	        }
				                  	        case 2: {
				                  	        	str = "中低风险" ;break ;
				                  	        }
				                  	        case 3: {
				                  	        	str = "中高风险" ;break ;
				                  	        }
				                  	        case 4: {
				                  	        	str = "高风险" ;break ;
				                  	        }
				                  	        default: {
				                  	        	str = "" ; 
				                  	        }
				                  		}
				                  		return str ;
			                  		}
			                  	},
			                  	{"data": "DeadRatio"},
								{"data": "DrugRatio", "render": function(obj, type, full){
										return formatNumber(full.DrugRatio)
									}},
								{"data": "MaterialRatio", "render": function(obj, type, full){
										return formatNumber(full.MaterialRatio)
									}}
			               ] ;
	// 外科组表格展示的列 
	var surGroupTableColumns =$.map(groupTableColumns, function(val, key) {
	    return val;
	});
    surGroupTableColumns.splice(8, 0, {"data": "AvgDaysBeforeOper"});
	var quotaCode = ['InCaseCnt','CMI','TotalWeight','AvgDays','AvgFee','RiskLevel','DeadRatio','DrugRatio','MaterialRatio'] ;
	var quotaCodes = quotaCode.join(",") ;
	// 外科组展示的指标
	var quotaCodesS = $.map(quotaCode,function(val,key){
		return val ;
	}) ;
	quotaCodesS.push('AvgDaysBeforeOper') ;
	quotaCodesS = quotaCodesS.join(",") ;
	loadTableDataKeyDisgroup("" ,quotaCodes,"allGroupTable",groupTableColumns);
	loadTableDataKeyDisgroup("I" ,quotaCodes,"intGroupTable",groupTableColumns);
	loadTableDataKeyDisgroup("S" ,quotaCodesS,"surGroupTable",surGroupTableColumns);
	loadTableDataKeyDisgroup("O" ,quotaCodes,"nonOperGroupTable",groupTableColumns);
	
	
	// 加载表格数据
	function loadTableDataKeyDisgroup(groupType ,quotaCode,tableId,columns){
		var param=drgUI.setAjaxData(tabId);
		param.quotaCode=quotaCode;
		param.monitorType="drgs";
		param.isKeyDisGroup= "1" ;
		param.groupType=groupType ;
		$.post(contextPath + "/DrgsIndexCal/indexCal.dhc", param).done(function(data){
			var paramsDataTables={searching:true,lengthChange:true,ordering:true,stateSave:false,info:false,scrollX:true,scrollY:'260px',autoWidth:false,orderCellsTop:true,tableTitle: "重点病组明细" };
			return $("#"+tabId+" #"+tableId).dataTableBasic(columns,data.data,paramsDataTables);
		});
	};
	
	var chartStatus = []  ;
	//不同重点病组类型页签的点击事件
	$('#'+tabId+' .groupTab').click(function() {
		var groupId = $(this).find("a").attr('href');//当前页签的ID
		var quotaTab = $('#'+tabId+' '+groupId).find("ul > li.quotasTab.active > a") ;
		if(jQuery.inArray(quotaTab.attr("href"), chartStatus) != -1) {
			// 判断象限图是否是线图，如果是不重新加载
			$('#'+tabId+' '+groupId).find(".btnslider").removeClass("btn-success").addClass("btn-warning");
			return ;
		}
		$('#'+tabId+' '+groupId).find('.quotasTab').unbind();//当前页签下指标对页签事件解除绑定
		//当前页签下指标对页签绑定点击事件
		$('#'+tabId+' '+groupId).find('.quotasTab').click(function() {
			/**
			 * 如果已经点击 病组指标变化 按钮 则不会重新请求，
			 */
			echartDivId =  $(this).find("a").attr("href") ; 
			if(jQuery.inArray(echartDivId, chartStatus) == -1) {
				$(this).parents("ul").find(".btnslider").removeClass("btn-warning").addClass("btn-success");
			} else {
				$(this).parents("ul").find(".btnslider").removeClass("btn-success").addClass("btn-warning");
				return ;
			}
			var quotasId = $(this).find("a").attr('href'); //指标对页签ID
			var quotas = quotasId.split("_").slice(1,3); //指标对
			var groupType = quotasId.split("_")[3]; //重点病组类型 I内科 S 外科 O 操作
			getKeyDisGroupQuotaData(quotasId,quotas,groupType); //加载当前指标对散点图数据
		})
		$('#'+tabId+' '+groupId).find('.quotasTab:eq(0)').click();//默认点击第一个指标对
	});
	$('#'+tabId+' .groupTab:eq(0)').click();//默认点击第一个病组类型
	/**
	 * 点击 病组指标变化幅度 按钮的事件
	 */
	$('#'+tabId+' .btnslider').click(function(){
		var groupTabId = $("#"+tabId+" .groupTab.active").find("a").attr('href');//当前页签的ID
		var quotasId = $('#'+tabId+' '+groupTabId).find('.quotasTab.active').find("a").attr('href');
		var dataId = quotasId.split("_");
		var quotaArr = quotasId.split('_').slice(1,3);
		var call = callBackDayFee;
		var xAxisTitle = "次均费用";
		var yAxisTitle = "药占比";
		if(dataId[1]=='AvgDays'&&dataId[2]=='AvgFee')
		{
			call = callBackDayFee;
			xAxisTitle = "平均住院日";
			yAxisTitle = "次均费用";
		}
		else
		{
			call = callBackFeeDrug;
		}
		dataId = dataId[1]+dataId[2]+dataId[3];
		var quotaData = paramTabPage[tabId]["quadData"][dataId] ;
		var config = quotaData.config;
		var compareType = $("#searchcq").children().eq(3).find("a.active").attr("data-value");
		var compareName = '';
		if (compareType == "year") {
			compareName = "同期";
		} else if (compareType == "month") {
			compareName = "上期";
		} else if (compareType == "manage") {
			compareName = "绩效";
		} else if (compareType == "std") {
			compareName = "标杆";
		}else if (compareType == "hosp") {
			compareName = "院内均值";
		}
		if($(this).hasClass("btn-success")){
			saveChartStatus($(this), chartStatus);
			var scatterChartData = [];
			var xAxis={"desc":xAxisTitle};
			var yAxis={"desc":yAxisTitle};
			var ids = orderScatterDataKDG(quotaData.xcur,quotaData.xlast,quotaData.ycur,quotaData.ylast,-1,-1);
			/**
			 * orderQuotaData @排序后的本期数据
			 */
			var orderQuotaData = {} ;
			orderQuotaData.xcur = [] ;
			orderQuotaData.ycur = [] ;
			for(var i = 0;i<ids.length;i++)
			{
				//线条从上期到本期
				var dataCoords=[[(quotaData.xlast[ids[i].xl].QuotaValue-quotaData.xlast[ids[i].xl].QuotaValuecc).toFixed(2),(quotaData.ylast[ids[i].yl].QuotaValue-quotaData.ylast[ids[i].yl].QuotaValuecc).toFixed(2)],[(quotaData.xcur[ids[i].xc].QuotaValue-quotaData.xcur[ids[i].xc].QuotaValuecc).toFixed(2), (quotaData.ycur[ids[i].yc].QuotaValue-quotaData.ycur[ids[i].yc].QuotaValuecc).toFixed(2)]];
				var dataValue=(i/ids.length*100).toFixed(2);
				scatterChartData.push({'symbol':'circle','symbolSize':6,"coords":dataCoords, value:dataValue,index:ids.length-i,code:quotaData.ylast[ids[i].yl].ccode,desc:quotaData.ylast[ids[i].yl].ddesc})
			}
			
			
			var chartParams={visualMap:true};
	    	/**
			 * callback_click @echart图点击事件的回调函数
			 */
			chartParams.callback_click = function(value){
				callBackDayFee(value) ;
			}
			/**
			 * callback_range @echart图值域选择后的回调函数
			 */
			chartParams.callback_range = function(param){
				var range_s = param.selected[0];
				var range_e = param.selected[1];
				var length = ids.length;
				range_s = (100 - range_s)*length/100;
				range_e = (100 - range_e)*length/100;
				var rangeQuotaData = {} ;
				rangeQuotaData.xcur = [] ;
				rangeQuotaData.ycur = [] ;
				for(var i=Math.ceil(range_e); i<=range_s && i< ids.length; i++){
					rangeQuotaData.xcur.push({"QuotaValuecc":quotaData.xcur[ids[i].xc].QuotaValuecc,"QuotaValue":quotaData.xcur[ids[i].xc].QuotaValue,"ccode":quotaData.xcur[ids[i].xc].ccode,"ddesc":quotaData.xcur[ids[i].xc].ddesc});
					rangeQuotaData.ycur.push({"QuotaValuecc":quotaData.ycur[ids[i].yc].QuotaValuecc,"QuotaValue":quotaData.ycur[ids[i].yc].QuotaValue,"ccode":quotaData.ycur[ids[i].yc].ccode,"ddesc":quotaData.ycur[ids[i].yc].ddesc});
				fillQuotaTable($("#"+tabId+ " "+quotasId).find("table"),rangeQuotaData,quotaArr) ;
				}
			}
			chartParams.formatterFunc=function (params) {
	        	var str="";
	        	var index=params.data.index;
	        	str+=params.data.code+'-'+params.data.desc+"<br>上期:("+params.data.coords[0][0]+","+params.data.coords[0][1]+")<br>本期("+params.data.coords[1][0]+","+params.data.coords[1][1]+")";        	
	        	return str;
	    	};
			if(config && config.xmin!=undefined){
				xAxis.xmin = config.xmin;
			}
			if(config && config.xmax!=undefined){
				xAxis.xmax = config.xmax;
			}
			if(config && config.ymin!=undefined){
				yAxis.ymin = config.ymin;
			}
			if(config && config.ymax!=undefined){
				yAxis.ymax = config.ymax;
			}
			linesChartBasic($("#"+tabId+" "+quotasId + " div:eq(0)"),scatterChartData,xAxis,yAxis,'',xAxisTitle+"和"+yAxisTitle+"与"+compareName+"差值象限分析图",'',chartParams);
			/**
			 * 按照默认的值域调用回调函数以显示象限表格
			 */
			chartParams.callback_range({selected:[80,100]});
		}else{
			/**
			 * 隐藏 值域选择，恢复散点图
			 */
			var xyAx = {"xAxis":{"desc":xAxisTitle},"yAxis":{"desc":yAxisTitle}};
			saveChartStatus($(this) , chartStatus)
			var scatterChartData = [{"desc":"本期","data":[]}];
			var xmin = 999999999;
			var xmax = -999999999;
			var ymin = 999999999;
			var ymax = -999999999;
			for(var i = 0;i<quotaData.xcur.length;i++){
				if(quotaData.xcur[i].QuotaValuecc!=null&&quotaData.ycur[i].QuotaValuecc!=null){
					var x = (quotaData.xcur[i].QuotaValue-quotaData.xcur[i].QuotaValuecc).toFixed(2);
					var y = (quotaData.ycur[i].QuotaValue-quotaData.ycur[i].QuotaValuecc).toFixed(2);
					if(x<xmin)
					{xmin = x;}
					if(x>xmax)
					{ xmax = x;}
					if(y<ymin)
					{ ymin = y;}
					if(y>ymax)
					{ ymax = y;}
					var color = "";
					if(x>=0 && y>=0){
						color = '#f05a72';
					}else if(x>0 &&y<0){
						color = '#fed503';
					}else if(x<0 && y>0){
						color = '#5bc0de';
					}else{
						color = '#66cc66';
					}
					scatterChartData[0].data.push({"ccode":quotaData.xcur[i].ccode,"ddesc":"("+quotaData.xcur[i].ccode+")"+quotaData.xcur[i].ddesc,"xdata":x,"ydata":y,"color":color});
				}
			}
			var chartParams=config;
			chartParams.isDataZoom=true;
			//散点图提示框处理函数
			chartParams.formatterFunc=function (params) {
		    	//修改散点图悬浮框显示样式(黑框)
		    	var str="";
		    	str+=params.name+ "<br/>" +"("+params.data.value[0]+","+params.data.value[1]+")"; 
		    	return str;
	    	};
	    	//点击事件
	    	chartParams.callBack_click=callBackDayFee;
			scatterChartsWithLine($("#"+tabId+" "+quotasId + " div:eq(0)"),scatterChartData,xyAx,xAxisTitle+"和"+yAxisTitle+"与"+compareName+"差值象限分析图",null,chartParams);
			fillQuotaTable($("#"+tabId+ " "+quotasId).find("table"),quotaData,quotaArr) ;
		}
	});
	
	getDisGroupCollectInfo();
	paramTabPage[tabId].loading=1;
});
	/**
	 * 加载所有科室,并绑定事件
	 * @
	 * @void
	 * @ Discription:
	 * @keyDiseaseGroupAnalysis.js
	 */
	function loadAllDepKeyDisGroup() {
		$.post(contextPath + "/DrgsIndexCal/findAllDepByHospCode.dhc").done(
				function(res) {
					var deps = res.data;
					deps = [ {
						DEPCODE : "",
						DEPNAME : "全院重点病组分析"
					} ].concat(deps);
					$CommonUI.combobox($("#" + tabId + " #depID"), deps, "DEPNAME",
						"DEPCODE", {
							"height" : 28,// 设定框的高度
							"onSelect" : function(n, o) {
								paramTabPage[tabId].oldDepCode = n.DEPCODE;
								paramTabPage[tabId].depName = n.DEPNAME;
								if(n.DEPCODE == "") { // 选择了全院
									paramTabPage[tabId].depCode = "" ;
									paramTabPage[tabId].pardepCode = "" ;
								}
								searchByCondition();
							} ,
							"onLoadSuccess" : function(){ 
								var data = $("#"+tabId+" #depID").combobox('getData');
								if(data.length>0 && paramTabPage[tabId].oldDepCode){
									$("#"+tabId+" #depID").combobox('setValue',paramTabPage[tabId].oldDepCode);
								}
							} 
						});
				});
	}

	//绘制表格
	//更改表格样式，并增加翻页功能
	function drawKeyDisGroupTable(data, columns, divId){
		var paramsDataTables={autoWidth:false,tableTitle:'重点病组指标情况表'};
		$("#"+tabId+" #"+divId).dataTableBasic(columns,data,paramsDataTables);
		
	}

	//重点病种筛选
	function keyDisGroupFilter(){
		 $.post( contextPath + '/pages/common/top-dialog.jsp').done(function(data){
				var dialog  = $(data);
				dialog.find(".modal-dialog").attr("id","keyDiseaseGroupFilter_dialog_id");
				dialog.find(".modal-title").html("重点病组筛选");
				dialog.modal({
					keyboard: false
				}).on({'hidden.bs.modal' : function(){
						$(this).remove();
						searchByCondition();
					   },'shown.bs.modal' : function(){
						   var desc = "" ;
						   if(paramTabPage[tabId].depName == undefined || paramTabPage[tabId].depName == "全院重点病组分析" ) {
							   desc = "全院"  ;
						   } else {
							   desc = paramTabPage[tabId].depName ;
						   }
						    var str="";
						    str+="";
						    str+=" <div class='row rowhcq'> ";
						    str+=" <div class='col-xs-12'> ";
						    str+="  <div class='boxcq clearfix'> ";
						    str+="     <div class='ti'><i class='fa fa-file-text-o'></i>"+desc+"重点病组筛选</div> ";
						    str+="      <ul class='nav nav-tabs boxnavcq' role='tablist'></ul> ";
						    str+="       <div class='clearfix'></div> "; 
						    str+="      <div class='col-xs-12' style = 'margin: 10px 0px;'> ";
						    str+="      	<div class='col-xs-6'> ";
						    str+="      		<div>    ";
						    str+="  			<div class='col-xs-5'> <label class='pull-right' style = 'height:30px;line-height:30px;'>筛选时间范围</label> </div>  ";
						    str+=" 	            <div class='col-xs-3'> <select id = 'keyDisGroupSelect' class='multiselect ' multiple='multiple'> </select> </div>    ";
						    str+="             	<div class='col-xs-4'> <button class='form-control pull-right btn btn-success' onclick = 'setKeyDisGroup()'> 确定</button> </div>  ";
						   /* str+="             	<div class='col-xs-4'> <a href=\"javascript:setKeyDisGroup()\"> 确定 </a> </div>  ";*/
						    str+=" 	      </div>      ";
						    str+="     <div class='clearfix'> </div>   ";
						    str+="      		<div>   ";
						    str+="         			<div class='col-xs-5'> <label class='pull-right' style = 'height:30px;line-height:30px;'>入组病例数占比排名前</label> </div>   ";
						    str+="              	<div class='col-xs-3'> <div class='input-group'>  <input class='form-control sliderValue' type='text' value = '80'/> <div class= 'input-group-addon'>%</div> </div> </div>  ";
						    str+="               	<div class='col-xs-4'> <input class='filterSlider' type='text'/> </div>  ";
						    str+="       		</div>  ";
						    str+="         		<div class='clearfix'></div>   ";
						    str+="    		<div>    ";
						    str+="   			    <div class='col-xs-5'> <label class='pull-right' style = 'height:30px;line-height:30px;'>总权重占比排名前</label> </div>   ";
						    str+="   	            <div class='col-xs-3'> <div class='input-group'> <input class='form-control sliderValue' type='text' value = '80'/> <div class='input-group-addon'>%</div> </div> </div> ";  
						    str+="   	            <div class='col-xs-4'> <input class='filterSlider' type='text'/> </div>   ";
						    str+="           		</div>   ";
						    str+="          		<div class='clearfix'> </div>  ";
						    str+="          		<div>    ";
						    str+="           			<div class='col-xs-5'> <label class='pull-right' style = 'height:30px;line-height:30px;'>各MDC内病组权重占比排名前</label> </div>   ";
						    str+="   	            	<div class='col-xs-3'> <div class='input-group'> <input class='form-control sliderValue' type='text' value = '80'/> <div class='input-group-addon' >%</div>  </div> </div>  ";
						    str+="   	            	<div class='col-xs-4'> <input class='filterSlider' type='text'/> </div>   ";
						    str+="          		</div>  ";
						    str+="          	</div>  ";
						    str+="       	<div class='col-xs-6'>   ";
						    str+="         		<div class='zhujie' style = 'padding:5px;line-height:30px; border-radius: 10px;box-shadow: 0 15px 80px rgba(0, 0, 0, .2);'>   ";
						    str+="        			1、将各DRG病组的入组病例数由高到低排名，取占总病组数排名前<span id = 'groupCntPer'>80</span>%病组；<br/>   ";
						    str+="        			2、将各DRG病组的总权重由高到低排名，取占总病组数排名前<span id = 'weightPer'>80</span>%病组；<br/>    ";
						    str+=" 					3、将各MDC内的DRG病组按照权重排名，取占总病组数排名前<span id = 'mdcWeightPer'>80</span>%病组；<br/>     ";
						    str+=" 					4、同时满足前三个条件病组为重点病组。     ";
						    str+="   		</div>    ";
						    str+="  	</div>       ";
						    str+="   </div>          ";
						    str+="   <div class='col-xs-12'> <div id='keyDisGroupMdcDiv'></div> </div>     ";
						    str+="   </div>     ";
						    str+="   </div>     ";
						    str+="   </div>     ";
						    
							dialog.find(".modal-dialog").width(1200);
							dialog.find(".modal-body").empty();
							dialog.find(".modal-body").append(str);
							var perConfig = [];
							var yearConfig = [];
							var years = [];
							var code = $("#"+tabId+" #depID").combobox('getValue');//科室代码
							if(code =="")
							{//选择全院的情况下 修改代码为Hosp
								code = "Hosp";
							}
							//加载筛选时间范围
							$.ajax({
								url : contextPath + "/keyDisGroup/getKeyFilterInit.dhc",
								type : "post",
								dataType : "json",
								async : false,
								data : {code:code},
								success : function(result) {
									years = result.data.years;
									var cfg = result.data.cfg;
									if(cfg!=""){
										yearConfig= cfg.split("θ")[0].split(",");
										perConfig= cfg.split("θ")[1].split(",");
									}
									var optStr = "";
									for(var i = 0;i<years.length;i++){
										optStr = optStr + "<option value="+years[i]+">"+years[i]+"</option>";
									}
									dialog.find("#keyDisGroupSelect").append(optStr);
								}
							});
							//多选下拉框初始化
							if(yearConfig.length==0&&years.length>0){
								dialog.find(".multiselect").multiselect('select', years[years.length-1]);//截取最后一个
							}else if(yearConfig.length>0){
								dialog.find(".multiselect").multiselect('select', yearConfig);
							}
							if(perConfig.length==0){
								//调整滑块
								dialog.find(".filterSlider").slider({//把滑块的最小值调整到0
									min: 0, max: 100, range: false, value: 80,
								    reversed : false
								});
							}else{
								//调整滑块
								dialog.find(".filterSlider:eq(0)").slider({//把滑块的最小值调整到0
									min: 0, max: 100, range: false, value: perConfig[0],
								    reversed : false
								});
								dialog.find(".sliderValue:eq(0)").val(perConfig[0]);
								dialog.find("#groupCntPer").html(perConfig[0]);
								
								//调整滑块
								dialog.find(".filterSlider:eq(1)").slider({//把滑块的最小值调整到0
									min: 0, max: 100, range: false, value: perConfig[1],
								    reversed : false
								});
								dialog.find(".sliderValue:eq(1)").val(perConfig[1]);
								dialog.find("#weightPer").html(perConfig[1]);
								//调整滑块
								dialog.find(".filterSlider:eq(2)").slider({//把滑块的最小值调整到0
									min: 0, max: 100, range: false, value: perConfig[2],
								    reversed : false
								});
								dialog.find(".sliderValue:eq(2)").val(perConfig[2]);
								dialog.find("#mdcWeightPer").html(perConfig[2]);
							}
							dialog.find(".filterSlider:eq(0)").on("slide", function(slideEvt) {
								var groupCntPerValue=slideEvt.value;
								$(this).parent().parent().find("input:eq(0)").val(slideEvt.value);
								dialog.find("#groupCntPer").html(groupCntPerValue);
							});
							dialog.find(".filterSlider:eq(1)").on("slide", function(slideEvt) {
								var weightPerValue=slideEvt.value;
								$(this).parent().parent().find("input:eq(0)").val(weightPerValue);
								dialog.find("#weightPer").html(weightPerValue);
							});
							dialog.find(".filterSlider:eq(2)").on("slide", function(slideEvt) {
								var mdcWeightPerValue=slideEvt.value;
								$(this).parent().parent().find("input:eq(0)").val(mdcWeightPerValue);
								dialog.find("#mdcWeightPer").html(mdcWeightPerValue);
							});
							//input 框值改变事件
							dialog.find(".sliderValue:eq(0)").blur(function(e){  
								var perValue=$(this).val();
								if(!/^([1-9]\d?|100)$/.test(perValue))
								{
									drgUI.warning('请输入0-100之间的整数');
									$(this).val(80);
									dialog.find(".filterSlider:eq(0)").slider("setValue",80);
									dialog.find("#groupCntPer").html(80);
									return;
								}
								dialog.find(".filterSlider:eq(0)").slider("setValue",perValue);
								dialog.find("#groupCntPer").html(perValue);
							});
							dialog.find(".sliderValue:eq(1)").blur(function(e){  
								var perValue=$(this).val();
								if(!/^([1-9]\d?|100)$/.test(perValue))
								{
									drgUI.warning('请输入0-100之间的整数');
									$(this).val(80);
									dialog.find(".filterSlider:eq(1)").slider("setValue",80);
									dialog.find("#weightPer").html(80);
									return;
								}
								dialog.find(".filterSlider:eq(1)").slider("setValue",perValue);
								dialog.find("#weightPer").html(perValue);
							});
							dialog.find(".sliderValue:eq(2)").blur(function(e){  
								var perValue=$(this).val();
								if(!/^([1-9]\d?|100)$/.test(perValue))
								{
									drgUI.warning('请输入0-100之间的整数');
									$(this).val(80);
									dialog.find(".filterSlider:eq(2)").slider("setValue",80);
									dialog.find("#mdcWeightPer").html(80);
									return;
								}
								dialog.find(".filterSlider:eq(2)").slider("setValue",perValue);
								dialog.find("#mdcWeightPer").html(perValue);
							});
							dialog.find(".tooltip-arrow").css("display","none");
							dialog.find(".tooltip-inner").css("display","none");
							dialog.find(".slider").width(160);
							dialog.find("#keyDisGroupSelect").next(".btn-group").width(100);
							dialog.find("#keyDisGroupSelect").next(".btn-group").find("button").width(100);
							dialog.find(".sliderValue").width(66);
							
							showKeyDisGroupMdcLevel();//展示重点病组数据信息
							dialog.find(".modal-footer").css("display","none");
			              }
			      });

			});
	}
	/**
	 * 设置重点病组
	 */
	function setKeyDisGroup()
	{	var depCode = paramTabPage[tabId].depCode ;
		var newDialog=$("#keyDiseaseGroupFilter_dialog_id");
		var caseRatio = newDialog.find(".filterSlider:eq(0)").val();//入组病例数占比
		var weightRatio = newDialog.find(".filterSlider:eq(1)").val();//总权重占比
		var mdcWeightRatio = newDialog.find(".filterSlider:eq(2)").val();//mdc权重占比
		var selected = [];
		newDialog.find(".multiselect option:selected").each(function () {
			selected.push($(this).val());
		});
		if(selected.length==0)
		{
			drgUI.warning('年份不能为空');
			return ;
		}
		
		drgUI.confirm({
			content : '确认后原重点病组将被清除?',
			callSure : function() {
				$.post(contextPath + '/keyDisGroup/setKeyDisGroup.dhc',
					{
						"years":selected,
						"caseCntPer":caseRatio,
						"weightPer":weightRatio,
						"mdcWeightPer":mdcWeightRatio,
						"depCode":depCode,
						"hospCode":paramTabPage[tabId].hospCode
					}
				).done(function(data){
					//显示遮罩层
					drgUI.success('本次确认'+(data.data?data.data:0)+'个重点病组');
					//清除全部缓存
					$.post(contextPath+"/ClearCache/clearCache.dhc",function(data){})
					//重新加载新的重点病组数据
					showKeyDisGroupMdcLevel();
				});
			}
		});
		
		
	}
	/**
	 * 从MDC 层次展示所有的重点病组
	 */
	function showKeyDisGroupMdcLevel(){
		var newDialog=$("#keyDiseaseGroupFilter_dialog_id");
		//重点病组已经确定 重点病组的详细取决于-->>筛选时间范围
		var selected = [];
		newDialog.find(".multiselect option:selected").each(function () {
			selected.push($(this).val());
		});
		newDialog.find('#keyDisGroupMdcDiv').html('<table id="keyDisGroupMdcTable" class="table"></table>');
		var depCode = paramTabPage[tabId].depCode ;
		$.post(contextPath+"/keyDisGroup/getKeyDisGroupDataMdc.dhc",{"years":selected,"depCode":depCode,"hospCode":paramTabPage[tabId].hospCode}).done(function(result){
			var columns=[
		                  	{"data": "DRGS","sClass": "details-control"},
		                  	{"data": "MDCCODE","title":'MDC',
		                  		"render": function(obj, type, full) {
		                  			return full["MDCCODE"]+"-"+full["MDCDESC"];
			                      }
	                  		},
		                  	{"data": "KEYGROUPCNT","title":'重点病组数' },
		                  	{"data": "CASECNT","title":'病例数',
	                  			"render": function(obj, type, full) {
	                  				if(full["CASECNT"]!=null) {
	                  					return full["CASECNT"] ;
	                  				} else {
	                  					return "-" ;
	              					}
			                      }
	              			},
		                  	{"data": "TOTALWEIGHT","title":'总权重',
	              				"render": function(obj, type, full) {
	                  				if(full["TOTALWEIGHT"]!=null){
	                  					return full["TOTALWEIGHT"] ; 
	                  				} else {
	                  					return "-";
	              					}
			                      }
		                  	},
		                  	{"data": "CMI","title":'CMI',
		                  		"render": function(obj, type, full) {
	                  				if(full["CMI"]!=null){
	                  					return full["CMI"] ;
	                  				} else {
	                  					return "-";
	              					}
			                      }
	                  		}
		                 ];
			var paramsDataTables={lengthChange:false,ordering:false,stateSave:true,info:false,tableTitle:'重点病组MDC',columnDefs:[{"orderable": false,"targets": [ 0 ] }]};
			paramsDataTables.buttons=[{"text": '增加病组',"action": function ( e, dt, node, config) {showAddKeyDisGroupDlg();}},{"text": '重点病组明细',"action": function ( e, dt, node, config) {showKeyDisGroupDrgDlg();}}];
			var oaTable=newDialog.find("#keyDisGroupMdcTable").dataTableBasic(columns,result.data,paramsDataTables);
				function format ( d ) {
				    // `d` is the original data object for the row
				    return '<div class="col-xs-12" style="background:#eee;">'
						    +'	<div class="row">'
					        +'		<div class="col-xs-12" id= "'+d+'"></div>'
					        +'   </div>'
					        +'</div>';
				}
				newDialog.find('#keyDisGroupMdcTable tbody').on('click', 'td.details-control', function () {
					var nTr = $(this).closest('tr');
					var row = oaTable.row( nTr );
			        var aData = row.data();
			        if (row.child.isShown()) //判断是否已打开
					{
						row.child.hide();
						nTr.removeClass("shown");
					} else {
						nTr.addClass("shown");
			        	var mdcCode = aData.MDCCODE ;
			        	row.child(format(mdcCode)).show();
			            keyDisGroupInMdc(mdcCode);
			        }
			    } );
		});
	}
	/**
	 * 新增重点病组
	 */
	function showAddKeyDisGroupDlg()
	{
		 $.post(contextPath + '/pages/common/top-dialog.jsp').done(function(data){
				var dialogadd  = $(data);
				dialogadd.find(".modal-dialog").attr("id","keyDiseaseGroupFilter_dialog_add");
				dialogadd.find(".modal-title").html("添加病组");
				dialogadd.modal({
					keyboard: false
				}).on({
					'hidden.bs.modal' : function(){
						$(this).remove();
					},
					'shown.bs.modal' : function(){
						dialogadd.find("#echartcq4").html("<table id = 'addKeyGroupTable' width = '100%'></table>");
						addKeyDisGroupTable();
					}
				});
		 });
	}
	/**
	 * 新增重点病组详细
	 * @returns
	 */
	function addKeyDisGroupTable()
	{
		var newDialog=$("#keyDiseaseGroupFilter_dialog_add");
		var addKeyDisGroupTableData = getExtraDisGroup();
		var columns=[
	                 {"data": "MDCCODE","title":"MDC代码"},
	               	 {"data": "DRGCODE" ,"title":"DRG代码"},
	               	 {"data": "DRGDESC","title":"DRG描述",
	           			"render": function(obj, type, full) {
		              				if(full["DRGDESC"]!=null) {
		              					return full["DRGDESC"] ;
		              				} else {
		              					return "-";
		          					}
		                      }
	       			 },
	               	 {"data": "CASECNT","title":"病例数",
	       				"render": function(obj, type, full) {
	           					if(full["CASECNT"]!=null){
	           						return full["CASECNT"] ;
	           					} else {
	               					return "-";
	           					}
		                      }
	   				 },
	                 {"data": "CASECNTRANGE","title":"病例数排名",
	   					"render": function(obj, type, full) {
	       						if(full["CASECNTRANGE"]!=null){
	       							return full["CASECNTRANGE"] ;
	       						} else {
	               					return "-";
	           					}
		                      }
						},
	               	 {"data": "WEIGHT","title":"权重",
							"render": function(obj, type, full) {
		  							if(full["WEIGHT"]!=null) {
		  								return full["WEIGHT"] ;
		  							} else {
		              					return "-";
		          					}
		                      }
						},
	               	 {"data": "TOTALWEIGHT","title":"总权重",
							"render": function(obj, type, full) {
									if(full["TOTALWEIGHT"]!=null){
										return full["TOTALWEIGHT"] ;
		  							} else {
		              					return "-";
		          					}
		                      }
							},
	               	 {"data": "TOTALWEIGHTRANGE","title":"总权重排名",
								"render": function(obj, type, full) {
									if(full["TOTALWEIGHTRANGE"]!=null){
										return full["TOTALWEIGHTRANGE"] ;
	   							} else {
	               					return "-";
	           					}
		                      }
	           		 },
	               	 {"data": "operation","title":"操作",
	               		"render": function(obj, type, full) {
	               			return "<a href = \"javascript:addKeyDisGroup('"+full["DRGCODE"]+"')\">添加</a>";
		                      }
	           		 }
	               ];
		var paramsDataTables={lengthChange:false,info:false,columnDefs:[{"orderable": false,"targets": [ 9 ] }]};
		newDialog.find("#echartcq4 #addKeyGroupTable").dataTableBasic(columns,addKeyDisGroupTableData,paramsDataTables);
	}
	/**
	 * 获取重点病组以外的病组 让用户筛选
	 */
	function getExtraDisGroup()
	{	
		var depCode = paramTabPage[tabId].depCode ;
		var newDialog=$("#keyDiseaseGroupFilter_dialog_id");
		var selected = [];
		newDialog.find(".multiselect option:selected").each(function () {
			selected.push($(this).val());
		});
		var data = [];
		$.ajax({
			url : contextPath + "/keyDisGroup/getExtraDisGroup.dhc",
			type : "post",
			dataType : "json",
			data : {
				"years":selected,
				"depCode":depCode,
				"hospCode":paramTabPage[tabId].hospCode
			},
			async : false,
			success : function(result) {
				data = result.data;
			}
		});
		return data

	}
	/**
	 * 添加重点病组
	 * @param drgCode
	 */
	function addKeyDisGroup(drgCode)
	{	
		var depCode = paramTabPage[tabId].depCode ;
		$.post(contextPath + '/keyDisGroup/addKeyDisGroup.dhc',{"drgCode":drgCode,"depCode":depCode}).done(function(data){
			//清除全部缓存
			$.post(contextPath+"/ClearCache/clearCache.dhc",function(data){});
			//刷新当前表格和mdc表格
			showKeyDisGroupMdcLevel();
			addKeyDisGroupTable();
			drgUI.success('添加病组成功');
		});
	}
	/**
	 * 重点病组详细对话框
	 */
	function showKeyDisGroupDrgDlg()
	{
		 $.post(contextPath + '/pages/common/top-dialog.jsp').done(function(data){
				var dialog  = $(data);
				dialog.find(".modal-title").html("重点病组明细");
				dialog.find(".modal-dialog").attr("id","keyDiseaseGroupFilter_dialog_dis");
				dialog.modal({
					keyboard: false
				}).on({
					'hidden.bs.modal' : function(){
						$(this).remove();
					},
					'shown.bs.modal' : function(){
						dialog.find("#echartcq4").html("<table id = 'keyGroupDetailTable' width = '100%' ><thead><tr><th>MDC代码</th><th>MDC描述</th><th>DRG代码</th><th>DRG描述</th><th>病例数</th><th>病例数排名</th><th>权重</th><th>总权重</th><th>总权重排名</th><th>操作</th></tr></thead><tbody></tbody></table>");
						keyDisGroupDrgDataTable()
					}
				});
		 });
	}
	
	/**
	 * 某个mdc下的重点病组
	 * @param mdc
	 */
	function keyDisGroupInMdc(mdc)
	{
		var newDialog=$("#keyDiseaseGroupFilter_dialog_id");
	    var tid='id'+new Date().getTime();
	    var mdcTableData = getKeyDisGroupDataDrg(mdc);
	    newDialog.find('#'+mdc).html('<table id="'+tid+'" class="table"></table>');
		var columns=[
	               	{"data": "DRGINFO","title":'DRG代码及描述',
	              		"render": function(obj, type, full) {
	          				if(full["DRGDESC"]!=null)
	      					{
	          					return full["DRGCODE"]+"-"+full["DRGDESC"];
	      					}
	          				else
	      					{
	          					return "("+full["DRGCODE"]+")";
	      					}
	                      }
	          		},
	              	{"data": "CASECNT","title":'病例数',
	          			"render": function(obj, type, full) {
	          				if(full["CASECNT"]!=null)
	      					{
	          					return full["CASECNT"];
	      					}
	          				else
	      					{
	          					return "-";
	      					}
	                      }
	          		},
	              	{"data": "TOTALWEIGHT","title":'总权重',
	          			"render": function(obj, type, full) {
	          				if(full["TOTALWEIGHT"]!=null)
	      					{
	          					return full["TOTALWEIGHT"];
	      					}
	          				else
	      					{
	          					return "-";
	      					}
	                      }
	          		},
	              	{"data": "WEIGHT","title":'权重',
	          			"render": function(obj, type, full) {
	          				if(full["WEIGHT"]!=null)
	      					{
	          					return full["WEIGHT"];
	      					}
	          				else
	      					{
	          					return "-";
	      					}
	                      }
	          		},
	              	{"data": "operation","title":'操作',
	              		"render": function(obj, type, full) {
	              			return "<a href = \"javascript:delKeyDisGroup('"+full.DRGCODE+"','mdclevel')\">删除</a>";
		            	   }
	          		}
	             ];
		var paramsDataTables={tableTitle:mdc+'-重点病组',lengthChange:false,ordering:false,stateSave:true,info:false,columnDefs:[{"orderable": false,"targets": [ 0 ] }]};
		newDialog.find("#"+tid).dataTableBasic(columns,mdcTableData,paramsDataTables);
	}
	/**
	 * 按照DRG层级获取重点病组的详情
	 * @param mdc 当mdc为空时查询所有mdc下的drg,当mdc不为空时查询特定mdc下的drg
	 */
	function getKeyDisGroupDataDrg(mdc)
	{
		var newDialog=$("#keyDiseaseGroupFilter_dialog_id");
		var selected = [];
		newDialog.find(".multiselect option:selected").each(function () {
			selected.push($(this).val());
		});
		var data = [];
		var depCode = paramTabPage[tabId].depCode ;
		$.ajax({
			url : contextPath + "/keyDisGroup/getKeyDisGroupDataDrg.dhc",
			type : "post",
			dataType : "json",
			data : {
				"years":selected,
				"mdcCode":mdc,
				"depCode":depCode,
				"hospCode":paramTabPage[tabId].hospCode
			},
			async : false,
			success : function(result) {
				data = result.data;
			}
		});
		return data;
	}
	/**
	 * 删除重点病组
	 * @param drg drg代码
	 * @param level 层级
	 */
	function delKeyDisGroup(drg,level)
	{	
		var depCode = paramTabPage[tabId].depCode ;
		drgUI.confirm({
			content : '确认删除吗?',
			callSure : function() {
				$.post(contextPath +"/keyDisGroup/delKeyDisGroup.dhc",{'drgCode':drg,'depCode':depCode},function(result){
					if(level=="mdclevel")
					{
						showKeyDisGroupMdcLevel();//重新加载MDC层级重点病组的详情
					}
					else
					{
						showKeyDisGroupMdcLevel();//重新加载MDC层级重点病组的详情
						keyDisGroupDrgDataTable();//重新加载DRG层级重点病组的详情
					}
					//清除全部缓存
					$.post(contextPath+"/ClearCache/clearCache.dhc",function(data){});
				});
			}
		});
	}

	/**
	 * 从drg层次展示重点病组信息
	 * @param container 对话框容器
	 * @param id table的id
	 */
	function keyDisGroupDrgDataTable()
	{
		var newDialog=$("#keyDiseaseGroupFilter_dialog_dis");
		var keyGroupDetailTableData = getKeyDisGroupDataDrg();
		var columns=[
	                 {"data": "MDCCODE" },
	                 {"data": "MDCDESC",
	             	  "render": function(obj, type, full) {
	             		  if(full["MDCDESC"]!=null) {
	             			  return full["MDCDESC"] ;
	             		  } else {
	         				  return "-";
	     				  }
	             	  }
	                 },
	               	{"data": "DRGCODE" },
	               	{"data": "DRGDESC",
	           			"render": function(obj, type, full) {
	           				if(full["DRGDESC"]!=null) {
	           					return full["DRGDESC"] ;
	           				}
	           				else {
	           					return "-";
	       					} 
		                     }
	       			},
	               	{"data": "CASECNT",
	       				"render": function(obj, type, full) {
	       					if(full["CASECNT"]!=null) {
	       						return full["CASECNT"];
	       					} else   {
	           					return "-";
	       					}
		                      }
	   				},
	               	{"data": "CASECNTRANGE",
	   					"render": function(obj, type, full) {
	   						if(full["CASECNTRANGE"]!=null){
	   							return full["CASECNTRANGE"] ;
	   						} else {
	           					return "-";
	       					} 
		                      }
						},
	               	{"data": "WEIGHT",
							"render": function(obj, type, full) {
								if(full["WEIGHT"]!=null) {
									return full["WEIGHT"] ;
								} else {
	           					return "-";
	       					}
		                      }
						},
	               	{"data": "TOTALWEIGHT",
							"render": function(obj, type, full) {
								if(full["TOTALWEIGHT"]!=null) {
									return full["TOTALWEIGHT"] ;
								} else {
	           					return "-";
	       					}
		                      }
							},
	               	{"data": "TOTALWEIGHTRANGE",
							"render": function(obj, type, full) {
								if(full["TOTALWEIGHTRANGE"]!=null) {
									return full["TOTALWEIGHTRANGE"] ;
								} else {
									return "-";
								}
	                     }
	           		},
	               	{"data": "operation",
	               		"render": function(obj, type, full) {
	               			return "<a href = \"javascript:delKeyDisGroup('"+full.DRGCODE+"','drglevel')\">删除</a>";//将full[0]改为full[2]   重点病组明细删除
		                      }
	           		}
	              ];
		var paramsDataTables={lengthChange:false,searching:false,stateSave:true,info:false,tableTitle:'',columnDefs:[{"orderable": false,"targets": [ 9 ] },{ "visible": false, "targets": [1]}]};
		newDialog.find("#echartcq4 #keyGroupDetailTable").dataTableBasic(columns,keyGroupDetailTableData,paramsDataTables);
	}

//获取病组的汇总信息
function getDisGroupCollectInfo()
{	
	var param=drgUI.setAjaxData(tabId);
	$.post(contextPath + "/keyDisGroup/getDisGroupCollectInfo.dhc",param).done(function(data){
		data = data.data[0] ;
		//环形图
		var labelTop = {
			    normal : {
			        label : {
			            show : true,
			            position : 'center',
			            formatter : function (params){
			            	return params.series.data[1].value+"/"+params.series.data[0].value ;
			            },
			            textStyle: {
			                baseline : 'bottom',
			                color: '#000'
			            }
			        },
			        labelLine : {
			            show : false
			        }
			    }
			};
			var labelFromatter = {
			    normal : {
			        label : {
			            formatter : function (params){
			            	return (params.series.data[1].value/params.series.data[0].value*100).toFixed(2) + '%'
			            },
			            textStyle: {
			                baseline : 'top'
			            }
			        }
			    }
			}
			var labelBottom = {
			    normal : {
			        color: '#ccc',
			        label : {
			            show : true,
			            position : 'center'
			        },
			        labelLine : {
			            show : false
			        }
			    },
			    emphasis: {
			        color: 'rgba(0,0,0,0)'
			    }
			};
			var radius = [50, 70];
			var legend={bottom : 'bottom',itemGap: 60,data:['重点病组个数','重点病组入组病例数','重点病组总权重']};
			var series=[
					        {
					            type : 'pie',
					            center : ['15%', '40%'],
					            radius : radius,
					            avoidLabelOverlap:false,
					            label: {
					                normal: {
					                	show : true,
							            position : 'center',
							            formatter : formatNumKeyDisGroup(data.KEYGROUPCNT,0)+"/"+formatNumKeyDisGroup(data.GROUPCNT,0)+"\n"+formatNumKeyDisGroup(100*data.KEYGROUPCNT/data.GROUPCNT,2)+"%",
							            textStyle: {
							                baseline : 'bottom'
							            }
					                }
					            },
					            data : [
					                {name:'重点病组个数', value:data.KEYGROUPCNT==null?0:data.KEYGROUPCNT},
					                {name:'other', value:(data.GROUPCNT==null?0:data.GROUPCNT)-(data.KEYGROUPCNT==null?0:data.KEYGROUPCNT)}
					            ]
					        },
					        {
					            type : 'pie',
					            center : ['45%', '40%'],
					            radius : radius,
					            avoidLabelOverlap:false,
					            label: {
					                normal: {
					                	show : true,
							            position : 'center',
							            formatter : formatNumKeyDisGroup(data.KEYCASECNT,0)+"/"+formatNumKeyDisGroup(data.CASECNT)+"\n"+formatNumKeyDisGroup(100*data.KEYCASECNT/data.CASECNT,2) +"%",
							            textStyle: {
							                baseline : 'bottom'
							            }
					                }
					            },
					            data : [
					                {name:'重点病组入组病例数', value:data.KEYCASECNT==null?0:data.KEYCASECNT},
					                {name:'other', value:(data.CASECNT==null?0:data.CASECNT)-(data.KEYCASECNT==null?0:data.KEYCASECNT)}
					            ]
					        },
					        {
					            type : 'pie',
					            center : ['75%', '40%'],
					            radius : radius,
					            avoidLabelOverlap:false,
					            label: {
					                normal: {
					                	show : true,
							            position : 'center',
							            formatter : formatNumKeyDisGroup(data.KEYTOTALWEIGHT,2)+"/"+formatNumKeyDisGroup(data.TOTALWEIGHT,2)+"\n"+formatNumKeyDisGroup(100*data.KEYTOTALWEIGHT/data.TOTALWEIGHT,2)+"%",
							            textStyle: {
							                baseline : 'bottom'
							            }
					                }
					            },
					            data : [
					                {name:'重点病组总权重', value: data.KEYTOTALWEIGHT==null?0:data.KEYTOTALWEIGHT},
					                {name:'other', value: (data.TOTALWEIGHT==null?0:data.TOTALWEIGHT)-(data.KEYTOTALWEIGHT==null?0:data.KEYTOTALWEIGHT)}
					                
					            ]
					        }
					    ];
		doughnutChart($('#'+tabId+' #keyGroupChart'),legend,series);
		//绘制饼图
		var groupType = [];//病组类型
		var groupTypeConfig = {"showLabel":false,"showLabelLine":false,radius:[0,'60%'],legendItemGap:5}
		groupType.push({name:'内科组',value:formatNumKeyDisGroup(data.INTERNALCNT,0)});
		groupType.push({name:'外科组',value:formatNumKeyDisGroup(data.SURGERYCNT,0)});
		groupType.push({name:'操作组',value:formatNumKeyDisGroup(data.OPERATIONCNT,0)});
		pieCharts($("#"+tabId+" #disGroupPropChart"), groupType, '病组类型分布占比', '',groupTypeConfig);
		var operLevel = [];//手术级别
		operLevel.push({name:'一级',value:data.LEVEL1});
		operLevel.push({name:'二级',value:data.LEVEL2});
		operLevel.push({name:'三级',value:data.LEVEL3});
		operLevel.push({name:'四级',value:data.LEVEL4});
		var operLevelConfig = {"showLabel":false,"showLabelLine":false,radius:[0,'60%'],legendItemGap:5}
		pieCharts($("#"+tabId+" #operLevPropChart"), operLevel, '主要手术级别占比', '',operLevelConfig);
	});
}

/**
xdata x轴数据
ydata y轴数据
xstd x轴标杆
ystd y轴标杆
xdirection x指标方向 1正向 -1负向
xdirection y指标方向 1正向 -1负向
*/
function orderScatterDataKDG(xcur,xlast,ycur,ylast,xdirection,ydirection)
{
	var better = [];
	var badder = [];
	var i = 0;
	var j = 0;
	var k = 0;
	var l = 0;
	
	while(i<xcur.length)
	{
		while(j<xlast.length)
		{
			if(xcur[i].ccode==xlast[j].ccode)
			{
				while(k<ycur.length)
				{
					if(xlast[j].ccode==ycur[k].ccode)
					{
						while(l<ylast.length)
						{
							if(ycur[k].ccode==ylast[l].ccode)
							{
								if(xcur[i].QuotaValue!=null&&xcur[i].QuotaValuecc!=null&&xlast[j].QuotaValue!=null&&xlast[j].QuotaValuecc!=null&&ycur[k].QuotaValue!=null&&ycur[k].QuotaValuecc!=null&&ylast[l].QuotaValue!=null&&ylast[l].QuotaValuecc!=null)
								{
									var x = xcur[i].QuotaValue/xcur[i].QuotaValuecc - xlast[j].QuotaValue/xlast[j].QuotaValuecc;
									var y = ycur[k].QuotaValue/ycur[k].QuotaValuecc - ylast[l].QuotaValue/ylast[l].QuotaValuecc;
									var distance = Math.sqrt(Math.pow(x,2)+Math.pow(y,2));
									if(xdirection*x>0&&ydirection*y>0)
									{
										//变好
										var change = {};
										change.xc = i;
										change.xl = j;
										change.yc = k;
										change.yl = l;
										change.distance = distance;
										better.push(change);
									}
									else
									{
										//变差
										var change = {};
										change.xc = i;
										change.xl = j;
										change.yc = k;
										change.yl = l;
										change.distance = distance;
										badder.push(change);
									}
								}
								l = l+1;
								break;
							}
							l = l+1;
						}
						k = k+1;
						break;
					}
					k = k+1;
				}
				j = j+1;
				break;
			}
			j = j+1;
		}
		i = i+1;
	}
	better.sort(function(a,b){
            return b.distance-a.distance});//降序
	badder.sort(function(a,b){
            return a.distance-b.distance});//升序
	var sortResult = [];
	for(var i=0;i<better.length;i++)
	{
		sortResult.push(better[i]);
	}
	for(var i=0;i<badder.length;i++)
	{
		sortResult.push(badder[i]);
	}
	//排序结果由好到差
	return sortResult;
} 

// 平均住院日和次均费用象限图
var configADAF_KeyDisGroupAnalysis = null  ;
// 次均费用和药占比象限图
var configAFDR_KeyDisGroupAnalysis = null  ;
// 判断是否是首次加载
var isFirstLoading = true ;
function getKeyDisGroupQuotaData(quotasId,quotas,groupType){	
	var  scatterAjaxCnt = 0;
	var compareType = $("#searchcq").children().eq(3).find("a.active").attr("data-value");
	//公共的参数
	var param=drgUI.setAjaxData(tabId);
	param.isGetCc = "1" ;
	param.monitorType = "drgs" ;
	param.isKeyDisGroup = "1" ;
	param.compareType = compareType ;
	var quotaData = {};
	if('All'!=groupType)
	{param.groupType = groupType;}//重点病组类型 All 全部 I 内科 S 外科  O 操作
	
	param.quotaCode = quotas[0];//指标1
	//指标1 本期值 + 标杆值
	$.post(contextPath + "/DrgsIndexCal/indexCal.dhc",param).done(function(result){
		quotaData.xcur = result.data;
		scatterAjaxCnt++;
	});
	//指标1 上期值 + 标杆值
	param.dateFrom = addMonth(paramTabPage[tabId].dateFrom,-1);
	param.dateTo = addMonth(paramTabPage[tabId].dateTo,-1);
	$.post(contextPath + "/DrgsIndexCal/indexCal.dhc",param).done(function(result){
		quotaData.xlast = result.data;
		scatterAjaxCnt++;
	});
	
	param.quotaCode = quotas[1];//指标2
	//指标2 本期值 + 标杆值
	param.dateFrom = paramTabPage[tabId].dateFrom;
	param.dateTo = paramTabPage[tabId].dateTo;
	$.post(contextPath + "/DrgsIndexCal/indexCal.dhc",param).done(function(result){
		quotaData.ycur = result.data;
		scatterAjaxCnt++;
	});
	
	//指标2 上期值 + 标杆值
	param.dateFrom = addMonth(paramTabPage[tabId].dateFrom,-1);
	param.dateTo = addMonth(paramTabPage[tabId].dateTo,-1);
	$.post(contextPath + "/DrgsIndexCal/indexCal.dhc",param).done(function(result){
		quotaData.ylast = result.data;
		scatterAjaxCnt++;
	});
	paramTabPage[tabId].compareType=param.compareType;//把条件筛选框中选择的比较类型赋值给页面中的compareType,来传给钻取下面的页面
	var scatterTimeInterval =  setInterval(function(){
		if(scatterAjaxCnt==4){
			clearInterval(scatterTimeInterval);
			var scatterChartData = [{"desc":"本期","data":[]}];
			// 同一种象限图避免重新计算 坐标轴范围
			if(configADAF_KeyDisGroupAnalysis == null && quotasId == "#allGroup_AvgDays_AvgFee_All"){
				configADAF_KeyDisGroupAnalysis = coordinateRange(quotaData,scatterChartData) ;
			} else {
				coordinateRange(quotaData,scatterChartData) ;
			}
			if(configAFDR_KeyDisGroupAnalysis == null && quotasId == "#allGroup_AvgFee_DrugRatio_All"){
				configAFDR_KeyDisGroupAnalysis = coordinateRange(quotaData,scatterChartData) ;
				return ;
			} else {
				coordinateRange(quotaData,scatterChartData) ;
			}
			var call = callBackFeeDrug ;
			var config = configAFDR_KeyDisGroupAnalysis ;
			var xAxisTitle = "次均费用";
			var yAxisTitle = "药占比";
			if(quotas[0]=='AvgDays'&&quotas[1]=='AvgFee')
			{
				xAxisTitle = "平均住院日";
				yAxisTitle = "次均费用";
				config = configADAF_KeyDisGroupAnalysis ;
				call = callBackDayFee ;
			}
			var xyAx = {"xAxis":{"desc":xAxisTitle},"yAxis":{"desc":yAxisTitle}};
			var compareType = $("#searchcq").children().eq(3).find("a.active").attr("data-value");
			var compareName = '';
			if (compareType == "year") {
				compareName = "同期";
			} else if (compareType == "month") {
				compareName = "上期";
			} else if (compareType == "manage") {
				compareName = "绩效";
			} else if (compareType == "std") {
				compareName = "标杆";
			}else if (compareType == "hosp") {
				compareName = "院内均值";
			}
			/**
			 * 绘制散点图
			 */
			if($("#"+tabId+ " "+quotasId).find("div:eq(0)")[0]!= undefined) {
				var chartParams=config;
				chartParams.isDataZoom=true;
				//散点图提示框处理函数
				chartParams.formatterFunc=function (params) {
			    	//修改散点图悬浮框显示样式(黑框)
			    	var str="";
			    	str+=params.name+ "<br/>" +"("+params.data.value[0]+","+params.data.value[1]+")";    
			    	return str;
		    	};
		    	//散点图点击事件
				chartParams.callBack_click=call;
	 			scatterChartsWithLine($("#"+tabId+ " "+quotasId).find("div:eq(0)"),scatterChartData,xyAx,xAxisTitle+"和"+yAxisTitle+"与"+compareName+"差值象限分析图",null,chartParams);
			}
			quotaData.config = config;
			fillQuotaTable($("#"+tabId+ " "+quotasId).find("table"),quotaData,quotas) ;
			if(paramTabPage[tabId]["quadData"] != null && paramTabPage[tabId]["quadData"] != undefined) {
				paramTabPage[tabId]["quadData"][quotas[0]+quotas[1]+groupType] = quotaData;
			}
			// 判断是否是首次加载
			if( isFirstLoading  == true ){
				// 加载加载次均费用和药占比
				getKeyDisGroupQuotaData("#allGroup_AvgFee_DrugRatio_All",["AvgFee", "DrugRatio"],"All") ;
				isFirstLoading = false ;
			}
		}
	}, 500);
	
	/**
	 * 求坐标轴范围
	 */
	function coordinateRange(quotaData,scatterChartData){
		var xmin = 999999999;
		var xmax = -999999999;
		var ymin = 999999999;
		var ymax = -999999999;
		for(var i = 0;i<quotaData.xcur.length;i++){
			var x = null;
			var y = null;
			if(quotaData.xcur[i].QuotaValuecc!=null&&quotaData.ycur[i].QuotaValuecc!=null){
				x = quotaData.xcur[i].QuotaValue-quotaData.xcur[i].QuotaValuecc;
				y = quotaData.ycur[i].QuotaValue-quotaData.ycur[i].QuotaValuecc;
				if(x<xmin)
				{xmin = x;}
				if(x>xmax)
				{ xmax = x;}
				if(y<ymin)
				{ ymin = y;}
				if(y>ymax)
				{ ymax = y;}
				x = x.toFixed(2)*1;
				y = y.toFixed(2)*1;
				var color = "";
				if(x>=0 && y>=0){
					color = '#f05a72';
				}else if(x>0 &&y<0){
					color = '#fed503';
				}else if(x<0 && y>0){
					color = '#5bc0de';
				}else{
					color = '#66cc66';
				}
				scatterChartData[0].data.push({"desc": quotaData.xcur[i].ccode + "(" + quotaData.xcur[i].ddesc+")" ,"ccode":quotaData.xcur[i].ccode,"xdata":x,"ydata":y,"color":color});
			}
		}
		for(var i = 0;i<quotaData.xlast.length;i++){
			var x = null;
			var y = null;
			if(quotaData.xlast[i].QuotaValuecc!=null&&quotaData.ylast[i].QuotaValuecc!=null){
				x = quotaData.xlast[i].QuotaValue-quotaData.xlast[i].QuotaValuecc;
				y = quotaData.ylast[i].QuotaValue-quotaData.ylast[i].QuotaValuecc;
				if(x<xmin)
				{xmin = x;}
				if(x>xmax)
				{ xmax = x;}
				if(y<ymin)
				{ ymin = y;}
				if(y>ymax)
				{ ymax = y;}
			}
		}
		xmin = Math.floor(xmin-0.2*Math.abs(xmin));
		ymin = Math.floor(ymin-0.2*Math.abs(ymin));
		xmax = Math.ceil(xmax+0.2*Math.abs(xmax));
		ymax = Math.ceil(ymax+0.2*Math.abs(ymax));
		var config = {"xmin":xmin,"xmax":xmax,"ymin":ymin,"ymax":ymax}
		return config ;
	}
}
//获取上年同期时间
function getLastYearTime(time)
{
	var last = time.split("-");
	last = (last[0]-1)+"-"+last[1];
	return last;
}
//填充象限图表格
var callbackKDG = callBackDayFee;
function fillQuotaTable(tableId,quotaData,quotas)
{	
	if(quotas[0]=='AvgDays'&&quotas[1]=='AvgFee')
	{
		callbackKDG = callBackDayFee;
	}
	else
	{
		callbackKDG = callBackFeeDrug;
	}
	quotaData.table = {"one":[],"two":[],"three":[],"four":[],"other":[]};
	for(var i = 0;i<quotaData.xcur.length;i++)
	{
		var x = null;
		var y = null;
		var param = {} ;
		param.data = {} ;
		if(quotaData.xcur[i].QuotaValuecc!=null&&quotaData.ycur[i].QuotaValuecc!=null)
		{
			x = quotaData.xcur[i].QuotaValue-quotaData.xcur[i].QuotaValuecc;
			y = quotaData.ycur[i].QuotaValue-quotaData.ycur[i].QuotaValuecc;
			x = x.toFixed(2)*1;
			y = y.toFixed(2)*1;
			param.data.value = [x,y] ;
			
			param.data.code = quotaData.xcur[i].ccode  ;
			param.data.drgDesc = quotaData.xcur[i].ddesc  ;//增加drg描述的参量
		}
		
		if(x==null&&y==null)
		{//不能进入象限的
			quotaData.table.other.push({"code":quotaData.xcur[i].ccode,"desc":quotaData.xcur[i].ddesc,"link":false});
		}
		else if(x<=0&&y<=0)//（0,0）归入第三象限，所以判断是否第三象限
		{//第三象限
            quotaData.table.three.push({"param":param, "code":quotaData.xcur[i].ccode,"desc":quotaData.xcur[i].ddesc,"link":false});
		}
		else if(x<0&&y>0)
		{//第二象限
			quotaData.table.two.push({"param":param, "code":quotaData.xcur[i].ccode,"desc":quotaData.xcur[i].ddesc,"link":false});
		}
		else if(x>=0&&y>=0)
		{//第一象限
            quotaData.table.one.push({"param":param, "code":quotaData.xcur[i].ccode,"desc":quotaData.xcur[i].ddesc,"link":false});

		}
		else if(x>0&&y<0)
		{//第四象限
			quotaData.table.four.push({"param":param, "code":quotaData.xcur[i].ccode,"desc":quotaData.xcur[i].ddesc,"link":false});
		}
	}
	
	tableId.empty();
	var quotaName1 = "次均费用";
	var quotaName2 = "药占比";
	if(quotas[0]=='AvgDays'&&quotas[1]=='AvgFee')
	{
		quotaName1 = "平均住院日";
		quotaName2 = "次均费用";
	}
	var tableStr = "";
	var quotaOneData = quotaData.table.one;//第一象限数据
	tableStr += "<tr>";
	tableStr += "<td width='20%'>I象限:"+quotaName1+"和"+quotaName2+"超标</td>";
	tableStr += "<td>";
	for(var i=0;i<quotaOneData.length;i++)
	{
			tableStr += '<a href=\'javascript:;\' onclick=\'callbackKDG('+JSON.stringify(quotaOneData[i].param)+')\'>' +  quotaOneData[i].code+"-"+quotaOneData[i].desc+"</a>、";
	}
	if(quotaOneData.length>0)
	{
		tableStr = tableStr.substr(0,tableStr.length-1);//去掉最后一个"、"
	}
	tableStr += "</td>";
	tableStr += "</tr>";
	var quotaTwoData = quotaData.table.two;//第二象限数据
	tableStr += "<tr>";
	tableStr += "<td width='20%'>II象限:"+quotaName2+"超标</td>";
	tableStr += "<td>";
	for(var i=0;i<quotaTwoData.length;i++)
	{
		tableStr += '<a href=\'javascript:;\' onclick=\'callbackKDG('+JSON.stringify(quotaTwoData[i].param)+')\'>' + quotaTwoData[i].code+"("+quotaTwoData[i].desc+')</a>、';
	}
	if(quotaTwoData.length>0)
	{
		tableStr = tableStr.substr(0,tableStr.length-1);//去掉最后一个"、"
	}
	tableStr += "</td>";
	tableStr += "</tr>";
	var quotaThreeData = quotaData.table.three;//第三象限数据
	tableStr += "<tr>";
	tableStr += "<td width='20%'>III象限:"+quotaName1+"和"+quotaName2+"未超标</td>";
	tableStr += "<td>";
	for(var i=0;i<quotaThreeData.length;i++)
	{
		if(quotaThreeData[i].param.data.value[0]=='0' && quotaThreeData[i].param.data.value[1]=='0'){//点在坐标原点时，不可钻取
			tableStr += quotaThreeData[i].code+"("+quotaThreeData[i].desc+")</a>、";
		}else{
		tableStr += '<a href=\'javascript:;\' onclick=\'callbackKDG('+JSON.stringify(quotaThreeData[i].param)+')\'>' +  quotaThreeData[i].code+"-"+quotaThreeData[i].desc+ '</a>、';
		}
	}
	if(quotaThreeData.length>0)
	{
		tableStr = tableStr.substr(0,tableStr.length-1);//去掉最后一个"、"
	}
	tableStr += "</td>";
	tableStr += "</tr>";
	var quotaFourData = quotaData.table.four;//第四象限数据
	tableStr += "<tr>";
	tableStr += "<td width='20%'>IV象限:"+quotaName1+"超标</td>";
	tableStr += "<td>";
	for(var i=0;i<quotaFourData.length;i++)
	{	
		tableStr += '<a href=\'javascript:;\' onclick=\'callbackKDG('+JSON.stringify(quotaFourData[i].param)+')\'>' +  quotaFourData[i].code+"-"+quotaFourData[i].desc+ '</a>、';
	}
	if(quotaFourData.length>0)
	{
		tableStr = tableStr.substr(0,tableStr.length-1);//去掉最后一个"、"
	}
	tableStr += "</td>";
	tableStr += "</tr>";
	var quotaOtherData = quotaData.table.other;//其他数据
	tableStr += "<tr>";
	tableStr += "<td width='20%'>其他数据</td>";
	tableStr += "<td>";
	for(var i=0;i<quotaOtherData.length;i++)
	{
		tableStr +=  quotaOtherData[i].code+"-"+quotaOtherData[i].desc+"、";
	}
	if(quotaOtherData.length>0)
	{
		tableStr = tableStr.substr(0,tableStr.length-1);//去掉最后一个"、"
	}
	tableStr += "</td>";
	tableStr += "</tr>";
	tableId.append(tableStr);
}

